package com.hnucm.c201901020241.discuss;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hnucm.c201901020241.R;
import com.hnucm.c201901020241.pojo.Content;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class Disscuss_item extends AppCompatActivity {

    ImageView back_IV,add_IV,shoucang_IV,jinghua_IV,rule_IV;
    String title,account;
    List<Content>contentList;
    RecyclerView recyclerView;
    MyAdapter myAdapter;
    int op;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_disscuss_item);
        init_action();//初始化各种点击事件
        title=getIntent().getStringExtra("title");
//        通过title和account来确定op的值
        x.Ext.init(getApplication());
        RequestParams requestParams = new RequestParams("http://121.4.27.254:8090/querychoucang?");
//        根据当前用户的账号和当前的标题来判断该用户是否收藏
        requestParams.addQueryStringParameter("title",title);
        requestParams.addQueryStringParameter("account",account);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println(result);
                if(result.equals("1")){
                    op=-1;shoucang_IV.setSelected(true);
                }
                else{
                    op=1;shoucang_IV.setSelected(false);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("MainActivity","ex"+ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
        //需要发送请求传递title参数给后端，后端根据title参数返回相应的论坛的各种信息
        //访问本地后台
        x.Ext.init(getApplication());
        requestParams = new RequestParams("http://121.4.27.254:8090/queryDiscuss?");
        requestParams.addQueryStringParameter("title",title);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i("MainActivity","result"+result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    ((TextView)findViewById(R.id.textView_title)).setText(title);
                    ((TextView)findViewById(R.id.textView_title_english)).setText(jsonObject.getString("title_english"));
                    ((TextView)findViewById(R.id.textView_shoucang)).setText(jsonObject.getString("shoucang"));
                    ((TextView)findViewById(R.id.textView10)).setText(jsonObject.getString("tiezi"));
                    ((TextView)findViewById(R.id.textView12)).setText(jsonObject.getString("administrator"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("MainActivity","ex"+ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

//        还要发送一个请求获得下面的一些简要的论坛帖子信息，设置为recyclerview
        x.Ext.init(getApplication());
        requestParams = new RequestParams("http://121.4.27.254:8090/queryContentList?");
        requestParams.addQueryStringParameter("title",title);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i("MainActivity2","result"+result);
                try {
                    JSONArray jsonArray=new JSONArray(result);
                    for(int i=0;i<jsonArray.length();i++){
                        Content content=new Content();
                        JSONObject jsonObject=jsonArray.getJSONObject(i);
                        content.title=jsonObject.getString("title");
                        content.name=jsonObject.getString("name");
                        content.time=jsonObject.getString("time");
                        content.base64=jsonObject.getString("base64");
                        content.title_discuss=jsonObject.getString("title_discuss");
                        content.minformation=jsonObject.getString("minformation");
                        content.account=jsonObject.getString("account");
                        contentList.add(content);
                    }
                    myAdapter=new MyAdapter();
                    recyclerView.setAdapter(myAdapter);
                    recyclerView.setLayoutManager(new LinearLayoutManager(Disscuss_item.this));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("MainActivity","ex"+ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

//        for(Content x:contentList){
//            System.out.println(x);
//        }



        //        刷新
        RefreshLayout refreshLayout = (RefreshLayout)findViewById(R.id.SmartRefreshLayout4);
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                refreshLayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                contentList.clear();
                x.Ext.init(getApplication());
                RequestParams requestParams = new RequestParams("http://121.4.27.254:8090/queryContentList?");
                requestParams.addQueryStringParameter("title",title);
                x.http().get(requestParams, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Log.i("MainActivity2","result"+result);
                        try {
                            JSONArray jsonArray=new JSONArray(result);
                            for(int i=0;i<jsonArray.length();i++){
                                Content content=new Content();
                                JSONObject jsonObject=jsonArray.getJSONObject(i);
                                content.title=jsonObject.getString("title");
                                content.name=jsonObject.getString("name");
                                content.time=jsonObject.getString("time");
                                content.base64=jsonObject.getString("base64");
                                content.title_discuss=jsonObject.getString("title_discuss");
                                content.minformation=jsonObject.getString("minformation");
                                content.account=jsonObject.getString("account");
                                contentList.add(content);
                            }
                            myAdapter.notifyDataSetChanged();
                            refreshLayout.finishRefresh(2000/*,false*/);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        Log.i("MainActivity","ex"+ex.getMessage());
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });

            }
        });
    }

    private void init_action() {
        SharedPreferences sharedPreferences = getSharedPreferences("user",MODE_MULTI_PROCESS);
        account =  sharedPreferences.getString("account","fault");
        recyclerView=findViewById(R.id.recyclerview1);
        contentList=new ArrayList<Content>();
        back_IV=findViewById(R.id.imageView2);
        add_IV=findViewById(R.id.imageView8);
        shoucang_IV=findViewById(R.id.imageView3);
        jinghua_IV=findViewById(R.id.imageView4);
        rule_IV=findViewById(R.id.imageView6);
        back_IV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        add_IV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Disscuss_item.this, Discuss_information.class);
                intent.putExtra("title",title);
                startActivity(intent);
            }
        });

        shoucang_IV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (shoucang_IV.isSelected()) {
                    shoucang_IV.setSelected(false);
                    op = -1;
                } else {
                    shoucang_IV.setSelected(true);
                    op = 1;
                }
                x.Ext.init(getApplication());
                RequestParams requestParams = new RequestParams("http://121.4.27.254:8090/changeShouCang?");
                requestParams.addQueryStringParameter("title",title);
                requestParams.addQueryStringParameter("op",op);
                requestParams.addQueryStringParameter("account",account);
                x.http().get(requestParams, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        System.out.println(result);
                        if(result.equals("1")&&op==1) Toast.makeText(Disscuss_item.this, "收藏成功", Toast.LENGTH_SHORT).show();
                        else if(result.equals("1")&&op==-1)Toast.makeText(Disscuss_item.this, "取消收藏", Toast.LENGTH_SHORT).show();
                        else Toast.makeText(Disscuss_item.this, "出现未知错误", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        Log.i("Discuss_item",ex.toString());
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }
        });


//        这两个区域还不知道咋写
        jinghua_IV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        rule_IV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(Disscuss_item.this).inflate(R.layout.discuss_content_item, parent, false);

            MyViewHolder myViewHolder = new MyViewHolder(view);

            return myViewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            holder.nameTv.setText(contentList.get(position).name);
            holder.titleTv.setText(contentList.get(position).title_discuss);
            holder.timeTv.setText(contentList.get(position).time);

            byte[] imageBytes = Base64.decode(contentList.get(position).base64, Base64.DEFAULT);
            Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
            holder.imageView.setImageBitmap(decodedImage);

//            发帖子
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    从这里将当前文章标题和当前论坛标题，发帖人作为参数传值，在数据库中建立一个表来记录每一个帖子中的详细回复信息
//                    数据库中建表，搜索的数据要和文章标题，当前论坛标题，发帖人一致才是对应的数据
//                    然后对于每一个人再开一个表，存自己发的帖子，
                    Intent intent=new Intent(Disscuss_item.this, Discuss_post_information.class);
                    intent.putExtra("title_discuss",contentList.get(position).title_discuss);
                    intent.putExtra("account",contentList.get(position).account);
                    intent.putExtra("name",contentList.get(position).name);
                    intent.putExtra("time",contentList.get(position).time);
                    intent.putExtra("mainInformation",contentList.get(position).minformation);
                    intent.putExtra("base64",contentList.get(position).base64);
                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return contentList.size();
        }
    }


    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView nameTv,titleTv,timeTv;
        ImageView imageView;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            nameTv = itemView.findViewById(R.id.textView_name);
            titleTv = itemView.findViewById(R.id.textView4_title);
            timeTv = itemView.findViewById(R.id.textView17);
            imageView = itemView.findViewById(R.id.imageView7);
            itemView.findViewById(R.id.imageView21).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(v.isSelected())v.setSelected(false);
                    else v.setSelected(true);
                }
            });
        }
    }
}